package net.stogi.unicore.beyond.ui.server.taskrunner.action.handler;

import net.stogi.common.gwt.dispatch.server.core.ActionHandler;
import net.stogi.common.gwt.dispatch.shared.exception.ActionException;
import net.stogi.unicore.beyond.api.exception.ValidationException;
import net.stogi.unicore.beyond.api.service.TaskService;
import net.stogi.unicore.beyond.ui.shared.taskrunner.action.model.RunTaskInstanceAction;
import net.stogi.unicore.beyond.ui.shared.taskrunner.action.model.RunTaskInstanceResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("UnicoreBeyondUi.Dispatch.RunTaskInstanceActionHandler")
public class RunTaskInstanceActionHandler implements ActionHandler<RunTaskInstanceAction, RunTaskInstanceResult> {

	private static final Logger log = LoggerFactory.getLogger(RunTaskInstanceActionHandler.class);
	
	@Autowired
	private TaskService taskService;
	
	@Override
	public RunTaskInstanceResult execute(RunTaskInstanceAction action) throws ActionException {
		RunTaskInstanceResult result = new RunTaskInstanceResult();
		
		try {
			taskService.runTaskInstance(action.getTaskInstance());
		}
		catch (ValidationException e) {
			log.warn("Exception occured while running task instance action", e);
			
			result.setMessages(e.getMessages());
		}
		
		return result;
	}

	@Override
	public Class<RunTaskInstanceAction> getActionType() {
		return RunTaskInstanceAction.class;
	}

	@Override
	public void rollback(RunTaskInstanceAction action, RunTaskInstanceResult result) throws ActionException {}
}
